// 发布订阅模式（EventEmitter）

type Callback = (...args: any[]) => void;

class EventEmitter {
  private events: Map<string, Callback[]> = new Map();

  // 订阅事件
  on(event: string, listener: Callback): void {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event)!.push(listener);
  }

  // 取消订阅
  off(event: string, listener: Callback): void {
    if (!this.events.has(event)) return;
    const listeners = this.events.get(event)!.filter(l => l !== listener);
    this.events.set(event, listeners);
  }

  // 只订阅一次
  once(event: string, listener: Callback): void {
    const onceWrapper = (...args: any[]) => {
      listener(...args);
      this.off(event, onceWrapper);
    };
    this.on(event, onceWrapper);
  }

  // 发布事件
  emit(event: string, ...args: any[]): void {
    if (!this.events.has(event)) return;
    this.events.get(event)!.forEach(listener => listener(...args));
  }
}

// 使用示例
const emitter = new EventEmitter();

function handler1(data: any) {
  console.log('handler1 收到:', data);
}

function handler2(data: any) {
  console.log('handler2 收到:', data);
}

emitter.on('test', handler1);
emitter.on('test', handler2);

emitter.emit('test', '第一次发布');

emitter.off('test', handler1);

emitter.emit('test', '第二次发布');

emitter.once('onceEvent', (msg) => {
  console.log('只触发一次:', msg);
});

emitter.emit('onceEvent', '只触发一次的事件');
emitter.emit('onceEvent', '不会再触发')

export {}